'use strict';

const Service = require('egg').Service;

class RoleService extends Service {
  async add(data) {
    const { ctx } = this;
    try {
      const res = await ctx.model.Role.create({
        ...data,
        createdTime: Date.now(),
      });
      return this.ctx.helper.success({ id: res.id }, '新增成功');
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async find(id) {
    const { ctx } = this;
    try {
      const res = await ctx.model.Role.findAll({
        attributes: [ 'id', 'roleName' ],
        where: { id, logicDelete: 0 },
      });
      return this.ctx.helper.success(res[0], '更新成功');
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async update({ roleName, id }) {
    const { ctx } = this;
    try {
      const res = await ctx.model.Role.update(
        { roleName, updatedTime: Date.now() },
        { where: { id } }
      );
      return this.ctx.helper.success(res[0]);
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async delete(id) {
    const { ctx } = this;
    try {
      const res = await ctx.model.Role.update(
        { logicDelete: 1 },
        { where: { id } }
      );
      return this.ctx.helper.success(res[0], '删除成功');
    } catch (e) {
      return this.ctx.helper.fail(e.name);
    }
  }

  async list(current = 1, pageSize = 10) {
    const { ctx } = this;
    try {
      const res = await ctx.model.Role.findAndCountAll({
        where: { logicDelete: 0 },
        order: [[ 'id', 'DESC' ]],
        offset: (current - 1) * pageSize, // 查询的起始下标
        limit: pageSize, // 查询的条数
      });
      return this.ctx.helper.success(res);
    } catch (e) {
      return this.ctx.helper.fail(e);
    }
  }

  async allList() {
    const { ctx } = this;
    try {
      const res = await ctx.model.Role.findAll({
        where: { logicDelete: 0 },
        order: [[ 'id', 'ASC' ]],
      });
      return this.ctx.helper.success(res);
    } catch (e) {
      return ctx.helper.fail(e);
    }
  }
}

module.exports = RoleService;
